package com.aurora.app.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.aurora.app.entity.CollectionThingStory;
import com.aurora.app.entity.StoryTopic;
import com.aurora.app.entity.Thing;
import com.aurora.app.entity.ThingStory;
import com.aurora.app.entity.ThingStoryComment;
import com.aurora.app.entity.ThingStoryImage;
import com.aurora.app.entity.User;
import com.aurora.app.enums.Level;
import com.aurora.app.exption.NullEntityException;
import com.aurora.app.service.CollectionThingStoryService;
import com.aurora.app.service.StoryTopicService;
import com.aurora.app.service.ThingStoryCommentService;
import com.aurora.app.service.ThingStoryImageService;
import com.aurora.app.service.ThingStoryService;
import com.aurora.app.service.UserService;
import com.aurora.app.util.DateUtils;
import com.aurora.app.util.StandardResponseBody;
import com.aurora.app.util.WhichLevel;
import com.aurora.base.dto.QueryResult;

@Controller
@RequestMapping(value = "api/square")
public class SquareController {
	@Resource
	private StoryTopicService storyTopicService;
	@Resource
	private ThingStoryService thingStoryService;
	@Resource
	private ThingStoryImageService thingStoryImageService;
	@Resource
	private ThingStoryCommentService thingStoryCommentService;
	@Resource
	private CollectionThingStoryService collectionThingStoryService;
	@Resource
	private UserService userService;
	
	/**
	 * 广场首页
	 * @param request
	 * @return
	 */
	@RequestMapping()
	public ModelAndView index(HttpServletRequest request){
		ModelAndView mv = new ModelAndView("square/square");
		return mv;
	}

	/**
	 * 某专题下的故事
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/story_list")
	public ModelAndView StoryList(HttpServletRequest request,@RequestParam() String topicId){
		System.out.println("-----------------------------------------------");
		ModelAndView mv = new ModelAndView("square/topic_story");
		mv.addObject("topicId", topicId);
		return mv;
	}
	
	/**
	 * 根据关注度获取列表
	 * @param request
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getTopicListByGuanzhu", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public String getTopicListByGuanzhu(HttpServletRequest request,int pageNum,int pageSize){
		List<StoryTopic> sList = this.storyTopicService.getListOrderByGuanZhu((pageNum-1)*pageSize, pageSize);
		List<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>();
		if(!CollectionUtils.isEmpty(sList)){
			for(StoryTopic storyTopic:sList){
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("IMG",storyTopic.getUrl());
				map.put("ID",storyTopic.getId());
				map.put("TITLE", storyTopic.getName());
				map.put("GUANGZHU", storyTopic.getLike());
				map.put("STORYNUM",storyTopic.getStoryNum() );
				map.put("DESC",storyTopic.getDesc());
				resultList.add(map);
			}
		}else{
			return StandardResponseBody.withPages(1, "", pageNum, true, null);			
		}
		
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("RESULTLIST", JSON.toJSONString(resultList));
		return StandardResponseBody.withPages(1, "", pageNum, false, map);
	}
	
	/**
	 * 根据上升速率获取列表
	 * @param request
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getTopicListByCreateRank", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public String getTopicListByCreateRank(HttpServletRequest request,int pageNum,int pageSize){
		List<StoryTopic> sList = this.storyTopicService.getListOrderByCreateNum((pageNum-1)*pageSize, pageSize);
		List<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>();
		if(!CollectionUtils.isEmpty(sList)){
			for(StoryTopic storyTopic:sList){
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("IMG",storyTopic.getUrl());
				map.put("ID",storyTopic.getId());
				map.put("TITLE", storyTopic.getName());
				map.put("GUANGZHU", storyTopic.getLike());
				map.put("STORYNUM",storyTopic.getStoryNum() );
				map.put("DESC",storyTopic.getDesc());
				resultList.add(map);
			}
		}else{
			return StandardResponseBody.withPages(1, "", pageNum, true, null);			
		}
		
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("RESULTLIST", JSON.toJSONString(resultList));
		return StandardResponseBody.withPages(1, "", pageNum, false, map);
	}
	
	/**
	 * 获取专题下的故事
	 * @param request
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getStoryList", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public String getStoryList(HttpServletRequest request,String topicId,int pageNum,int pageSize,String searchKey){
		List<ThingStory> tsList = this.thingStoryService.getListByTopicId((pageNum-1)*pageSize, pageSize,topicId,searchKey);
		List<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>();
		if(!CollectionUtils.isEmpty(tsList)){
			for(ThingStory thingStory:tsList){
				Map<String,Object> map = new HashMap<String,Object>();
				ThingStoryImage tsi = this.thingStoryImageService.getFirstImageByStoryThingId(thingStory.getId());
				if(tsi!=null){
					map.put("IMG",tsi.getPath());
				}
				map.put("ID",thingStory.getId());
				map.put("USERID", thingStory.getUser().getId());
				map.put("USERIMG", thingStory.getUser().getHeadimgurl());
				Level level = WhichLevel.getLevel(thingStory.getUser().getHuoyueIntegral(), thingStory.getUser().getJiaoyiIntegral());
				map.put("LEVEL", level.ordinal());
				map.put("COMMENTNUM", this.thingStoryCommentService.getCommentNum(thingStory));
				map.put("LIKE", thingStory.getZan());
				map.put("USERNICKNAME", thingStory.getUser().getNickName());
				map.put("TITLE", thingStory.getTitle());
				resultList.add(map);
			}
		}else{
			return StandardResponseBody.withPages(1, "", pageNum, true, null);			
		}
		
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("RESULTLIST", JSON.toJSONString(resultList));
		return StandardResponseBody.withPages(1, "", pageNum, false, map);
	}
	
	/**
	 * 获取故事详细
	 * @param request
	 * @param thingId
	 * @return
	 */
	@RequestMapping(value="storyDetail")
	public ModelAndView storyDetail(HttpServletRequest request,
			@RequestParam("STORY_ID") String storyId){
		ModelAndView mv = new ModelAndView("square/story_detail");
		ThingStory thingStory = this.thingStoryService.get(storyId);
		if(thingStory==null){
			throw new NullEntityException("无法获取物语");
		}
		List<ThingStoryImage> thingStoryImageList = this.thingStoryImageService.getListByThingStoryId(thingStory.getId());
		String time = DateUtils.getMyFormatTime(thingStory.getCreateTime());
		User user = thingStory.getUser();
		Level level = WhichLevel.getLevel(user.getHuoyueIntegral(), user.getJiaoyiIntegral());
		
		long commentNum = this.thingStoryCommentService.getCommentNum(thingStory);
		long collectionNum = this.collectionThingStoryService.getCollectionNum(thingStory);
		//获取前5条收藏
		List<CollectionThingStory> collectionUserList = this.collectionThingStoryService.getCollectionUser(thingStory, 0, 5);
		//是否收藏
		User userLook =(User) request.getSession().getAttribute("user");
		boolean isCollection = this.collectionThingStoryService.isCollection(userLook, thingStory);
		mv.addObject("commentNum",commentNum );
		mv.addObject("collectionNum",collectionNum );
		mv.addObject("collectionUserList",collectionUserList );
		mv.addObject("isCollection",isCollection );
		mv.addObject("sessionUser", userLook);
		mv.addObject("thingStory", thingStory);
		mv.addObject("time", time);
		mv.addObject("user", user);
		mv.addObject("level", level.ordinal());
		mv.addObject("thingStoryImageList", thingStoryImageList);
		return mv ;
	}
	
	@RequestMapping(produces = "text/plain;charset=UTF-8",value="getComment")
	@ResponseBody
	public String getComment(HttpServletRequest request,
			@RequestParam("THING_STORY_ID") String thingStoryId,
			@RequestParam("PAGEINDEX") Integer pageIndex,
			@RequestParam("PAGESIZE") Integer pageSize
			){
		QueryResult<ThingStoryComment> commentResult = this.thingStoryCommentService.getListByThingStoryByPages(thingStoryId, pageIndex, pageSize);
		List<ThingStoryComment> commentList = commentResult.getResults();
		Map<String,Object> responseMap = new  HashMap<String,Object>();
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		if(commentList!=null &&commentList.size()>0){
			for(ThingStoryComment comment:commentList){
				Map<String,Object> resultMap = new  HashMap<String,Object>();
				resultMap.put("HEADIMGURL",comment.getUser().getHeadimgurl());
				resultMap.put("USERID",comment.getUser().getId());
				resultMap.put("NICKNAME", comment.getUser().getNickName());
				resultMap.put("TIME", DateUtils.getMyFormatTime(comment.getCreateTime()));
				resultMap.put("CONTENT", comment.getContent());
				list.add(resultMap);
			}
		}
		responseMap.put("STATUS", "OK");
		responseMap.put("DESC", "返回成功");
		responseMap.put("RESULTLIST", JSON.toJSONString(list));
		responseMap.put("MSGNUM", this.thingStoryCommentService.getCommentNum(this.thingStoryService.get(thingStoryId)));
		return JSON.toJSONString(responseMap);
	}
	
	@RequestMapping(value="addComment")
	@ResponseBody
	public String addComment(HttpServletRequest request,
			@RequestParam("FROM_USER") String fromUserId,
			@RequestParam("TO_USER") String toUserId,
			@RequestParam("THING_STORY_ID") String thingStoryId,
			@RequestParam("CONTENT") String content){
		Map<String,Object> responseMap = new  HashMap<String,Object>();
		
		User from = this.userService.get(fromUserId);
		User to = this.userService.get(toUserId);
		ThingStory thingStory = this.thingStoryService.get(thingStoryId);
		if(from==null || to==null || thingStory == null){
			responseMap.put("STATUS", "ERR");
			responseMap.put("DESC", "找不到实体类");
			return JSON.toJSONString(responseMap);
		}
		ThingStoryComment comment = new ThingStoryComment();
		comment.setUser(from);
		comment.setToUser(to);
		comment.setThingStory(thingStory);
		comment.setContent(content);
		if(this.thingStoryCommentService.addComment(comment)){
			responseMap.put("STATUS", "OK");
			responseMap.put("DESC", "评论保存成功");
			return JSON.toJSONString(responseMap);
		}else{
			responseMap.put("STATUS", "ERR");
			responseMap.put("DESC", "评论保存异常");
			return JSON.toJSONString(responseMap);
		}
	}
	/**
	 * 收藏物品的取消和关注
	 * 
	 * @param request
	 * @param thingId
	 * @param isCollection
	 * @return
	 */
	@RequestMapping(value = "CollectionStory")
	@ResponseBody
	public String CollectionStory(HttpServletRequest request, @RequestParam("STORY_ID") String storyId,
			@RequestParam("isCollection") Boolean isCollection) {
		Map<String, Object> responseMap = new HashMap<String, Object>();
		ThingStory thingStory = this.thingStoryService.get(storyId);
		User user = (User) request.getSession().getAttribute("user");
		if (isCollection) {
			try {
				this.collectionThingStoryService.add(thingStory, user);
				responseMap.put("STATUS", "OK");
				responseMap.put("DESC", "关注此物语成功");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				responseMap.put("STATUS", "ERR");
				responseMap.put("DESC", "关注此物语失败");
			}
		} else {
			try {
				this.collectionThingStoryService.remove(thingStory, user);
				responseMap.put("STATUS", "OK");
				responseMap.put("DESC", "取消关注此物语成功");
			} catch (Exception e) {
				responseMap.put("STATUS", "ERR");
				responseMap.put("DESC", "取消关注此物语失败");
			}
		}

		return JSON.toJSONString(responseMap);
	}
}
